package com.java_demo.demo;

import com.java_demo.dao.ICustomerDao;
import com.java_demo.domain.Customer;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.List;

public class Demo_01 {
    public static void main(String[] args) {
        // mybatis的配置文件
        String resource = "mybatis-config.xml";
        // 使用类加载器加载mybatis的配置文件（它也加载关联的映射文件）
        InputStream is = Demo_01.class.getClassLoader().getResourceAsStream(resource);

        // 1. 构建sqlSession的工厂
        // SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);

        // 2.1 使用MyBatis提供的Resources类加载mybatis的配置文件（它也加载关联的映射文件）
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 2.2 构建sqlSession的工厂
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);

        // 创建能执行映射文件中sql的sqlSession
        SqlSession session = sessionFactory.openSession();

        ICustomerDao customerDao = session.getMapper(ICustomerDao.class);

        //执行查询返回一个唯一user对象的sql
        int i = customerDao.addCustomer("jason");
        System.out.println(i);

        Customer customer = customerDao.queryById(100L);
        System.out.println(customer);

        List<Customer> customers = customerDao.queryList(0, 100);
        System.out.println(customers);
        session.close();
    }
}
